package com.crm.system.service.impl.activityManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.activityManager.CustomerProductActivity;
import com.crm.model.entity.activityManager.CustomerProductActivityRelation;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.productManager.CustomerMemberProduct;
import com.crm.model.entity.productManager.CustomerProduct;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.activityManager.CustomerActivityAddQO;
import com.crm.model.qo.activityManager.CustomerProductActivityQO;
import com.crm.model.vo.activityManager.CustomerContractProductActivityVO;
import com.crm.model.vo.activityManager.CustomerProductActivityUpdateVO;
import com.crm.model.vo.activityManager.CustomerProductActivityVO;
import com.crm.model.vo.activityManager.CustomerRecentActivityVO;
import com.crm.model.vo.announcement.AnnouncementVO;
import com.crm.model.vo.customerContractManager.ContractUnpaidVO;
import com.crm.service.activityManager.CustomerProductActivityDbService;
import com.crm.service.activityManager.CustomerProductActivityRelationDbService;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.service.productManager.CustomerProductDbService;
import com.crm.system.service.activityManager.CustomerProductActivityService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author luojie
 * @date 2021/2/23 11:36
 */
@Service
public class CustomerProductActivityServiceImpl implements CustomerProductActivityService {

    @Autowired
    private CustomerProductActivityDbService productActivityDbService;
    @Autowired
    private CustomerProductActivityRelationDbService productActivityRelationDbService;
    @Autowired
    private CustomerProductDbService customerProductDbService;
    @Autowired
    private CustomerMemberProductDbService customerMemberProductDbService;

    /**
     * 活动管理--活动列表分页信息
     * @param customerProductActivityQO    ---活动列表查询参数
     * @param pageIndex/ pageSize          ---页码、分页大小
     * @param sortName/sortOrder           ---活动列表排序字段及规则
     * @author yincuimei
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductActivityVO> selectCustomerProductActivityVOList(CustomerProductActivityQO customerProductActivityQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        customerProductActivityQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerProductActivityVO> productActivityVOList = productActivityDbService.selectCustomerProductActivityVOList(customerProductActivityQO,order.toString());
        PageInfo<CustomerProductActivityVO> pageInfo = new PageInfo<CustomerProductActivityVO>(productActivityVOList);
        return new DhPageInfo<CustomerProductActivityVO>(pageInfo, productActivityVOList);
    }

    /**
     * 活动列表--根据活动ID查询活动信息(查看/编辑)
     * @param productActivityId  ---活动ID
     * @return
     */
    @Override
    public CustomerProductActivityUpdateVO selectCustomerProductActivityById(String productActivityId) {
        CustomerProductActivityUpdateVO productActivityUpdateVO = new CustomerProductActivityUpdateVO();

        //1. 查询活动表信息(chs_customer_product_activity)
        CustomerProductActivity customerProductActivity = productActivityDbService.selectProductActivityByPrimaryKey(productActivityId);
        if(customerProductActivity != null){
            productActivityUpdateVO.setProductActivityId(customerProductActivity.getProductActivityId());//活动ID
            productActivityUpdateVO.setProductActivityName(customerProductActivity.getProductActivityName());//活动名称
            productActivityUpdateVO.setActivityPeriodValidityStart(customerProductActivity.getActivityPeriodValidityStart());//活动有效期开始日期
            productActivityUpdateVO.setActivityPeriodValidityEnd(customerProductActivity.getActivityPeriodValidityEnd());//活动有效期结束日期
            productActivityUpdateVO.setActivityPriceRangeStart(customerProductActivity.getActivityPriceRangeStart());//活动价格区间起始价
            productActivityUpdateVO.setActivityPriceRangeEnd(customerProductActivity.getActivityPriceRangeEnd());//活动价格区间截止价
            productActivityUpdateVO.setActivityPrice(customerProductActivity.getActivityPrice());//活动价格
            productActivityUpdateVO.setExchangeMethod(customerProductActivity.getExchangeMethod());//兑换方式
        }

        //2. 查询产品表信息(chs_customer_product)
        List<HashMap> productActivityList = new ArrayList<HashMap>();
        List<CustomerProductActivityRelation> customerProductActivityRelationList =  productActivityRelationDbService.selectProductDropDownSelectedListByActivityId(productActivityId);
        customerProductActivityRelationList.stream().forEach(customerProductActivityRelation -> {
            HashMap hashMap = new HashMap();
            String productId = customerProductActivityRelation.getCustomerProductId();
            if("0".equals(customerProductActivityRelation.getProductCategories())){
                //非会员
                CustomerProduct customerProduct = customerProductDbService.selectCustomerProductByProductId(productId);
                hashMap.put("productId",productId);
                hashMap.put("productName",customerProduct.getProductName());
                hashMap.put("productFinalPrice",customerProductActivityRelation.getProductFinalPrice());
            }else {
                //会员
                CustomerMemberProduct customerMemberProduct = customerMemberProductDbService.selectMemberProductById(productId);
                hashMap.put("productId",productId);
                hashMap.put("productName",customerMemberProduct.getMemberCardName());
                hashMap.put("productFinalPrice",customerProductActivityRelation.getProductFinalPrice());
            }
            productActivityList.add(hashMap);
        });
        if(productActivityList != null && productActivityList.size() > 0){
            productActivityUpdateVO.setCustomerProductList(productActivityList);//产品信息
        }
        return productActivityUpdateVO;
    }

    /**
     *活动管理--添加活动
     * @param customerActivityAddQO
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public int addProductActivity(CustomerActivityAddQO customerActivityAddQO) {
        int result = 0;
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //活动名称
        String productActivityName = customerActivityAddQO.getProductActivityName();
        //有效期起始日期
        Date activityPeriodValidityStart = customerActivityAddQO.getActivityPeriodValidityStart();
        //有效期截止日期
        Date activityPeriodValidityEnd = customerActivityAddQO.getActivityPeriodValidityEnd();

        //查询有没有重复的活动（活动名称相同，起始时间和结束时间不在重复范围内）
        List<CustomerProductActivity> customerProductActivities = productActivityDbService.selectActivityIfRepeated(productActivityName,activityPeriodValidityStart,activityPeriodValidityEnd);
        if(customerProductActivities.size()>0){
            //有活动名称、起始时间、结束时间相同的活动,判断产品是否相同
            for (CustomerProductActivity customerProductActivity : customerProductActivities) {
                String activityId = customerProductActivity.getProductActivityId();
                List<CustomerProductActivityRelation> customerProductActivityRelationList = productActivityRelationDbService.selectProductDropDownSelectedListByActivityId(activityId);
                List<String> selectProductIdList = customerProductActivityRelationList.stream().map(CustomerProductActivityRelation::getCustomerProductId).collect(Collectors.toList());
                //如果产品相同则有重复活动，直接返回
                List<String> productIdList = new ArrayList<>();
                for (HashMap hashMap : customerActivityAddQO.getProductList()) {
                    productIdList.add(hashMap.get("productId").toString());
                }
                if(ListUtils.isEqualList(selectProductIdList,productIdList)){
                    result = 1;
                    return result;
                }
            }
        }

        //活动价格区间起始价
        BigDecimal activityPriceRangeStart = customerActivityAddQO.getActivityPriceRangeStart();
        //活动价格区间截止价
        BigDecimal activityPriceRangeEnd = customerActivityAddQO.getActivityPriceRangeEnd();
        //活动价
        BigDecimal activityPrice = customerActivityAddQO.getActivityPrice();
        //兑换方式
        String exchangeMethod = customerActivityAddQO.getExchangeMethod();
        //活动id
        String activityId = CommonUtils.getGUID();

        CustomerProductActivity customerProductActivity = new CustomerProductActivity();
        customerProductActivity.setProductActivityId(activityId);
        customerProductActivity.setProductActivityName(productActivityName);
        customerProductActivity.setActivityPriceRangeStart(activityPriceRangeStart);
        customerProductActivity.setActivityPriceRangeEnd(activityPriceRangeEnd);
        customerProductActivity.setActivityPeriodValidityStart(activityPeriodValidityStart);
        customerProductActivity.setActivityPeriodValidityEnd(activityPeriodValidityEnd);
        customerProductActivity.setActivityPrice(activityPrice);
        customerProductActivity.setExchangeMethod(exchangeMethod);
        //上架状态
        String shelfStatus = "0";
        customerProductActivity.setActivityShelfStatus(shelfStatus);
        customerProductActivity.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        customerProductActivity.setCreatePeopleId(userAccount.getAccountId());
        customerProductActivity.setCreateTm(new Date());
        customerProductActivity.setUpdatePeopleId(userAccount.getAccountId());
        customerProductActivity.setUpdateTm(new Date());
        productActivityDbService.insertProductActivity(customerProductActivity);

        //保存产品表
        List<HashMap> productIdList = customerActivityAddQO.getProductList();
        productIdList.stream().forEach(productHash ->{
            CustomerProductActivityRelation customerProductActivityRelation = new CustomerProductActivityRelation();
            customerProductActivityRelation.setProductActivityRelationId(CommonUtils.getGUID());
            customerProductActivityRelation.setProductActivityId(activityId);
            customerProductActivityRelation.setCustomerProductId(productHash.get("productId").toString());
            customerProductActivityRelation.setCreatePeopleId(userAccount.getAccountId());
            customerProductActivityRelation.setProductCategories(productHash.get("productCategories").toString());
            customerProductActivityRelation.setCreateTm(new Date());
            if(productHash.get("productFinalPrice")!=null){
                customerProductActivityRelation.setProductFinalPrice(new BigDecimal(productHash.get("productFinalPrice").toString()));
            }
            productActivityRelationDbService.insertProductActivityRelation(customerProductActivityRelation);
        });
        return result;
    }

    /**
     * 活动列表--活动上下架操作
     * @param productActivityId    ---活动主键
     * @param activityShelfStatus  ---上下架状态(0:上架;1:下架)
     * @author yincuimei
     * @return
     */
    @Override
    public Boolean updateActivityShelfStatus(String productActivityId, String activityShelfStatus) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        return productActivityDbService.updateActivityShelfStatus(productActivityId,activityShelfStatus,userAccount.getAccountId());
    }

    /**
     * 活动列表--(活动上架)根据活动ID查询活动是否在有效期内
     * @param productActivityId ---活动ID
     * @author yincuimei
     * @return
     */
    @Override
    public Boolean selectActivityIsInValidityPeriod(String productActivityId) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return productActivityDbService.selectActivityIsInValidityPeriod(productActivityId,dateFormat.format(new Date()));
    }

    /**
     * 活动列表--编辑活动
     * @param customerActivityAddQO
     * @return
     */
    @Override
    public int editProductActivity(CustomerActivityAddQO customerActivityAddQO) {
        int result = 0;

        //查询有没有名称和有效期相同的活动，查询后直接返回
        List<CustomerProductActivity> customerProductActivityList = productActivityDbService.selectActivityIfRepeatedNotSelf(customerActivityAddQO.getProductActivityId(),customerActivityAddQO.getProductActivityName(),customerActivityAddQO.getActivityPeriodValidityStart(),customerActivityAddQO.getActivityPeriodValidityEnd());
        if(customerProductActivityList.size()>0){
            //有活动名称、起始时间、结束时间相同的活动,判断产品是否相同
            for (CustomerProductActivity customerProductActivity : customerProductActivityList) {
                String activityId = customerProductActivity.getProductActivityId();
                List<CustomerProductActivityRelation> customerProductActivityRelationList = productActivityRelationDbService.selectProductDropDownSelectedListByActivityId(activityId);
                List<String> selectProductIdList = customerProductActivityRelationList.stream().map(CustomerProductActivityRelation::getCustomerProductId).collect(Collectors.toList());
                //如果产品相同则有重复活动，直接返回
                if(ListUtils.isEqualList(selectProductIdList,customerActivityAddQO.getProductList())){
                    result = 1;
                    return result;
                }
            }
        }
        //删除活动
        CustomerProductActivity customerProductActivity = new CustomerProductActivity();
        customerProductActivity.setProductActivityId(customerActivityAddQO.getProductActivityId());
        customerProductActivity.setProductActivityName(customerActivityAddQO.getProductActivityName());
        customerProductActivity.setActivityPeriodValidityStart(customerActivityAddQO.getActivityPeriodValidityStart());
        customerProductActivity.setActivityPeriodValidityEnd(customerActivityAddQO.getActivityPeriodValidityEnd());
        customerProductActivity.setActivityPriceRangeStart(customerActivityAddQO.getActivityPriceRangeStart());
        customerProductActivity.setActivityPriceRangeEnd(customerActivityAddQO.getActivityPriceRangeEnd());
        customerProductActivity.setActivityPrice(customerActivityAddQO.getActivityPrice());
        customerProductActivity.setExchangeMethod(customerActivityAddQO.getExchangeMethod());
        productActivityDbService.updateProductActivityByPrimaryKey(customerProductActivity);

        //删除活动产品关系，重新添加
        productActivityRelationDbService.deleteActivityRelationByActivityId(customerActivityAddQO.getProductActivityId());
        //保存产品表
        List<HashMap> productIdList = customerActivityAddQO.getProductList();
        productIdList.stream().forEach(productHash ->{
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
            CustomerProductActivityRelation customerProductActivityRelation = new CustomerProductActivityRelation();
            customerProductActivityRelation.setProductActivityRelationId(CommonUtils.getGUID());
            customerProductActivityRelation.setProductActivityId(customerActivityAddQO.getProductActivityId());
            customerProductActivityRelation.setCustomerProductId(productHash.get("productId").toString());
            customerProductActivityRelation.setProductCategories(productHash.get("productCategories").toString());
            if(productHash.get("productFinalPrice")!=null){
                customerProductActivityRelation.setProductFinalPrice(new BigDecimal(productHash.get("productFinalPrice").toString()));
            }
            customerProductActivityRelation.setCreatePeopleId(userAccount.getAccountId());
            customerProductActivityRelation.setCreateTm(new Date());
            productActivityRelationDbService.insertProductActivityRelation(customerProductActivityRelation);
        });
        return result;
    }


    @Override
    public DhPageInfo<CustomerContractProductActivityVO> selectValidityPeriodCustomerActivityList(Integer pageIndex, Integer pageSize, String searchInfo) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        //customerProductActivityQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        List<CustomerProductActivity> productActivityVOList = productActivityDbService.selectValidityPeriodCustomerActivityList(searchInfo);

        PageInfo<CustomerProductActivity> pageInfo = new PageInfo<>(productActivityVOList);
        List<CustomerContractProductActivityVO> result = new ArrayList<CustomerContractProductActivityVO>();
        for(CustomerProductActivity dbItem:pageInfo.getList()) {
            CustomerContractProductActivityVO customerContractProductActivityVO = new CustomerContractProductActivityVO(dbItem);
            //查询活动下产品
            List<CustomerProductActivityRelation> customerProductActivityRelations = productActivityRelationDbService.selectProductDropDownSelectedListByActivityId(dbItem.getProductActivityId());
            List<HashMap> productList = new ArrayList<>();
            Boolean ifMemberActivity = false;
            for(CustomerProductActivityRelation productActivityRelation:customerProductActivityRelations) {
                String productId = productActivityRelation.getCustomerProductId();
                if("0".equals(productActivityRelation.getProductCategories())){
                    CustomerProduct customerProduct = customerProductDbService.selectCustomerProductByProductId(productId);
                    HashMap product = new HashMap();
                    product.put("productId", productId);
                    product.put("productName", customerProduct.getProductName());
                    product.put("productCategories",productActivityRelation.getProductCategories());
                    product.put("productFinalPrice",productActivityRelation.getProductFinalPrice());
                    if ("1".equals(productActivityRelation.getProductCategories())) {
                        ifMemberActivity = true;
                    }
                    productList.add(product);
                }else {
                    CustomerMemberProduct customerMemberProduct = customerMemberProductDbService.selectMemberProductById(productId);
                    HashMap product = new HashMap();
                    product.put("productId", productId);
                    product.put("productName", customerMemberProduct.getMemberCardName());
                    product.put("productCategories",productActivityRelation.getProductCategories());
                    product.put("productFinalPrice",productActivityRelation.getProductFinalPrice());
                    if ("1".equals(productActivityRelation.getProductCategories())) {
                        ifMemberActivity = true;
                    }
                    productList.add(product);
                }

            }
            customerContractProductActivityVO.setProductList(productList);
            customerContractProductActivityVO.setIfMemberActivity(ifMemberActivity);
            result.add(customerContractProductActivityVO);
        }
        return new DhPageInfo<CustomerContractProductActivityVO>(pageInfo, result);
    }

    /***
     * @Description:任务管理-任务列表 查询近期活动列表
     * @Author: luojie
     * @Date: 2021/4/26 16:45
     */
    @Override
    public DhPageInfo<CustomerRecentActivityVO> selectRecentActivityList() {
        //设定显示5条数据
        Integer pageIndex = 1;
        Integer pageSize = 5;
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<CustomerRecentActivityVO> customerRecentActivityVOList= new ArrayList<>();
        List<CustomerProductActivity> customerContractList = productActivityDbService.selectRecentActivityList();
        PageInfo<CustomerProductActivity> pageInfo = new PageInfo<>(customerContractList);
        pageInfo.getList().stream().forEach(customerProductActivity -> {
            CustomerRecentActivityVO customerRecentActivityVO = new CustomerRecentActivityVO();
            customerRecentActivityVO.setProductActivityName(customerProductActivity.getProductActivityName());
            customerRecentActivityVO.setActivityPeriodValidityStart(customerProductActivity.getActivityPeriodValidityStart());
            customerRecentActivityVO.setActivityPeriodValidityEnd(customerProductActivity.getActivityPeriodValidityStart());
            customerRecentActivityVOList.add(customerRecentActivityVO);
        });
        return new DhPageInfo<CustomerRecentActivityVO>(pageInfo, customerRecentActivityVOList);
    }
}
